﻿using System;
using System.IO;

namespace DNFImagePacks2Manager.Helpers
{
    public class DirectoryHelper
    {
        public static void MoveDirectory(string sourceDirName, string destDirName, bool overwrite = false)
        {
            if (!Directory.Exists(sourceDirName))
            {
                throw new DirectoryNotFoundException("源目录不存在: " + sourceDirName);
            }

            if (Directory.Exists(destDirName))
            {
                if (overwrite)
                {
                    Directory.Delete(destDirName, recursive: true);
                }
                else
                {
                    throw new IOException("目标目录已存在且不允许覆盖: " + destDirName);
                }
            }

            string? sourceRoot = Path.GetPathRoot(sourceDirName);
            string? destRoot = Path.GetPathRoot(destDirName);

            if (sourceRoot == null && destRoot == null) {
                throw new IOException("无法获取目标根目录");
            }

            if (string.Equals(sourceRoot, destRoot, StringComparison.OrdinalIgnoreCase))
            {
                Directory.Move(sourceDirName, destDirName);
            }
            else
            {
                string? destDir = Path.GetDirectoryName(destDirName) ?? throw new IOException("创建目标目录失败");
                Directory.CreateDirectory(destDir);

                CopyDirectory(sourceDirName, destDirName);

                Directory.Delete(sourceDirName, recursive: true);
            }
        }

        private static void CopyDirectory(string sourceDir, string destDir)
        {
            Directory.CreateDirectory(destDir);

            foreach (string file in Directory.GetFiles(sourceDir))
            {
                string destFile = Path.Combine(destDir, Path.GetFileName(file));
                File.Copy(file, destFile, overwrite: true);
            }

            foreach (string subDir in Directory.GetDirectories(sourceDir))
            {
                string destSubDir = Path.Combine(destDir, Path.GetFileName(subDir));
                CopyDirectory(subDir, destSubDir);
            }
        }
    }
}
